<!DOCTYPE html>
<html  xmlns="http://www.w3.org/1999/xhtml"
       xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"/>
    <meta name="robots" content="noindex, nofollow"/>
    <meta name="format-detection" content="telephone=no"/>
    <title>呼出测试</title>
    <script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="../js/layui/layui.js"></script>
    <link rel="stylesheet" href="../js/layui/css/layui.css" />
    <style>
        body{font-size:12px;}
        input{width:150px;height:30px;border:1px solid #ccc;}
        select{width:120px;height:22px;}
        table{border-collapse:collapse;border:none;margin-top:100px;}
        table td{line-height:50px; width:300px;}
        button{width:150px;height:30px;}
    </style>
</head>

<body>
<table border="1" align="center">
    <tr style="display: none;">
        <td width="230">客户号码:<input id="mainCallPhone" value="" /></td>
        <td></td>
    </tr>
    <tr>
        <td>客户号码:<input id="targetCallPhone" value="" /></td>
        <td></td>
    </tr>
    <tr style="display: none;">
        <td>主显号:<input id="showNum" value="" /></td>
        <td></td>
    </tr>
    <tr style="display:none;">
        <td>来源:
            <select id="whereFrom">
                <option value="0">APP</option>
                <option selected="selected" value="1">置业</option>
            </select>
        </td>
    </tr>
    <tr style="display:none;">
        <td>页面来源:
            <select id="pageFrom">
                <option value="0">app盘源</option>
                <option value="1">app联动call</option>
                <option value="2">置业盘源</option>
                <option value="3">置业联动call</option>
                <option value="4">电子客簿</option>
                <option value="5">测试座机页面</option>
                <option value="6">app拨号记录</option>
            </select>
        </td>
        <td></td>
    </tr>
    <tr style="display:none;">
        <td>城市:
            <select id="city">
                <option value="1">广州</option>
                <option value="2">东莞</option>
                <option value="3">佛山</option>
            </select>
        </td>
        <td></td>
    </tr>
    <tr style="display: none;">
        <td>呼出方:
            <select id="mainCallType">
                <option value="0">经纪</option>
                <option value="1">客户</option>
            </select>
        </td>
        <td></td>
    </tr>
    <tr style="display: none;">
        <td>提交线路:
            <select id="commitTo">
                <option value="0">东进</option>
                <option selected="selected" value="1">电信</option>
            </select>
        </td>
        <td></td>
    </tr>
    <tr >
        <td>客户名:<input id="customerName" value="测试" />
            <input id="createUserId" value="1" type="hidden"/>
        </td>
        <td></td>
    </tr>
    <tr >
        <td>项目名：
            <input id="projectName" type="text"/>
        </td>
        <td></td>
    </tr>
    <tr >
        <td>机器码&nbsp&nbsp：<input id="txToken"></td>
        <td></td>
    </tr>
    <tr >
        <td>经纪ID：<input id="txUserId" value="" /></td>
        <td></td>
    </tr>
    <tr>
        <td><button type="button" onclick="init()">连接</button></td>
        <td><button type="button" onclick="call()">呼叫</button>
        <button id="btnChangePc" onclick="btnChangePc()">确定切换电脑外呼</button>
        <button id="btnChangePcNot" onclick="btnChangePcNot()">不切换电脑外呼</button></td>
    </tr>
    <tr >
        <td colspan="2" style="width:100%;height: 100px;" align="left">状态:<input id="txResult"/></td>
    </tr>
</table>
<script type="text/javascript">
    var serverAddr = null;
//    serverAddr= "172.16.6.56:9990";
    serverAddr= "113.108.202.235:7771";
//                serverAddr = "113.108.202.235:8080";
//            serverAddr = "cloudcall.hfit.ihk.cn:8888";
    //            serverAddr = "172.16.200.44:8080";
    var url;
    var sessionId;
    var webSocket;
    var time = 0;
    //先获取用户ID
    $("#txToken").val("123321_"+uuid(16, 16));
    //    $("#txUserId").val(uuid(8, 16));
    //    var token = $("#txToken").val();
    //    var userId = $("#txUserId").val();

    var token = null;
    var userId = null;

    var layer = null;
    layui.use('layer', function(){
        layer = layui.layer;
    });

    function init() {

        token = $("#txToken").val();
        userId = $("#txUserId").val();

        if(userId == ""){
            layer.msg("经纪ID不能为空")
            return;
        }
        if(token == ""){
            layer.msg("机器码不能为空");
            return
        }

        url = "ws://"+serverAddr+"/wbs/browser/connect?token=" + token + "&userId=" + userId;

        webSocket = new WebSocket(url);

        $("#txResult").val("connecting");

        webSocket.onopen = function(event) {
            callback(event);
        };

        webSocket.onmessage = function(event) {
            callback(event);
        };

        webSocket.onclose = function(event) {
            callback(event);
        };

        webSocket.onerror = function(event) {
            callback(event);
        };

        //每100秒发一次心跳包
        //这里的回调不可以加括号()
        setInterval(heartbeat, 10000);

    };

    //代理方法，发送消息到服务器必须用这个方法
    function waitForConnection(todoMethod, interval) {
        if(webSocket.readyState == WebSocket.OPEN) {
            todoMethod();
        } else {
            setTimeout(function() {
                waitForConnection(todoMethod, interval);
            },interval);
        }
    }

        //
        function btnChangePc() {
            waitForConnection(function() {
                try {
                    webSocket.send(JSON.stringify({
                        msgType: "changePc",
                        token: token,
                        userId: userId
                    }));
                } catch (e) {
                    console.log("call error");
                    console.log(e);
                }
            }, 100);
        }

        function btnChangePcNot() {
            waitForConnection(function() {
                try {
                    webSocket.send(JSON.stringify({
                        msgType: "notChangePc",
                        token: token,
                        userId: userId
                    }));
                } catch (e) {
                    console.log("call error");
                    console.log(e);
                }
            }, 100);
        }


    //外呼
    function call() {
        var whereFrom = $("#whereFrom").val();
        var mainCallPhone = $("#mainCallPhone").val();
        var targetCallPhone = $("#targetCallPhone").val();
        var pageFrom = $("#pageFrom").val();
        var city = $("#city").val();
        var mainCallType = $("#mainCallType").val();
        var commitTo = $("#commitTo").val();
        var customerName = $("#customerName").val();
        var showNum = $("#showNum").val();
        var txUserId = $("#txUserId").val()
        var txToken = $("#txToken").val()
        var projectName = $("#projectName").val()

        if(targetCallPhone == ""){
            layer.msg("客户号码不能为空")
            return;
        }
        if(txUserId == ""){
            layer.msg("经纪ID不能为空")
            return;
        }
        if(txToken == ""){
            layer.msg("机器码不能为空");
            return
        }
        if(customerName == ""){
            layer.msg("客户名不能为空")
            return;
        }
        if(projectName == ""){
            layer.msg("项目名不能为空")
            return;
        }
        waitForConnection(function() {
            try {
                webSocket.send(JSON.stringify({
                    msgType: "CALL",
                    sessionId:"sid-"+uuid(8, 16),
                    mainCallPhone:"13724059427",
                    targetCallPhone:targetCallPhone,
                    whereFrom:1,
                    city:1,
                    mainCallType:1,
                    commitTo:2,
                    customerName:customerName,
                    machineFrom:txToken,
                    createUserId:txUserId,
                    pageFrom:2,
                    propertyNo:"xxx",
                    project:projectName,
                    isHide:"true",
                    dataId:0
                }));

            } catch (e) {
                console.log("call error");
                console.log(e);
            }
        }, 100);
    }

    //发送心跳包
    var repeatTimes = 0;
    function heartbeat() {
        if(webSocket.readyState == WebSocket.OPEN) {
            try {
                webSocket.send(JSON.stringify({
                    msgType: "BEAT",
                    token: token
                }));
                console.log("heart beat:"+new Date());
            } catch (e) {
                console.log("call error");
                console.log(e.errMesg);
            }
        }
    }

    //回调
    var  res = "";
    var lay = null;
    function callback(event) {
        var txResult = $("#txResult");
        var result;
        console.log(new Date());
        console.log(event);
        switch (event.type) {
            case "open":
                txResult.val("已连接，请拨号");
                break;
            case "message":
                res += "接收->" + event.data+"\r\n";
                result = JSON.parse(event.data);
                txResult.val(result.desc);
                sessionId =result['sessionId'];
                if(result.msgType == "COMMIT_SUCCESS"){
                    time = new Date().getTime();
                }
                var msg = callbackMsgType(result);
                if(msg == "客户无法接通"){
                    var s = new Date().getTime();
                    if((s - time) < 3000){
                        msg = "客户拒接";
                    }
                }
                if((lay == null || lay == "" || lay == undefined ) && result.msgType != "WEBSOCKET_CONNECT_MSG"){
                    var html = "<div id='msg' align='center' style='line-height: 200px;font-size:30px;'>"+msg+"</div>";
                    lay = layer.open({
                        type:1,
                        title:"呼叫提示",
                        closeBtn:1,
                        content:html,
                        area: ['500px', '300px'],
                        cancel:function(res){
                            layer.close(res);
                            lay = null;
                        }
                    });
                }else{
                    $("#msg").html(msg);
                }
                break;
            case "error":
                txResult.val(event.data);
                break;
            case "close":
                txResult.val("连接已断开");
                break;
                defualt:
                        break;
        }
    }

    function callbackMsgType(result){
        var desc = result.desc;
        var msgType = result.msgType;
        var msg = "";
        switch (msgType){
            case "COMMIT_SUCCESS":
                msg = "正在为您呼叫客户,请稍候...";
                break;
            case "MAIN_RINGING":
                msg = "正在等候客户接听电话...";
                break;
            case "MAIN_ANSWERED":
                msg = "客户已接通，请您稍候接听电话...";
                break;
            case "TARGET_RINGING":
                msg = "请您接听电话...";
                break;
            case "TARGET_ANSWERED":
                msg = "通话中...";
                break;
            case "MAIN_DISCONNECTED":
                msg = "结束通话...";
                break;
            case "MAIN_FAILED": //主叫失败
                msg = desc;
                break;
            case "TARGET_FAILED"://被叫失败
                msg = desc;
                break;
            case "COMMIT_FAILED"://提交失败
                msg = "提交失败";
                break;
            case "TARGET_DISCONNECTED"://被叫挂断
                msg = "结束通话";
                break;
            case "APP_START":
                msg = "APP开始呼叫";
                break;
            case "APP_STOP":
                msg = "APP结束通话";
                break;
            case "APP_DISCONNECT":
                msg = "APP断开";
                break;
            case "EXCEPTION"://异常标识
                msg = desc;
                break;
            case "WEBSOCKET_TOO_MANY_CONNECT_MSG":
                msg = "请勿使用2个以上窗口或浏览器进行外呼";
                break;
            default:
                break;
        }
        return msg;
    }

    function uuid (len, radix) {
        // Private array of chars to use
        var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var chars = CHARS, uuid = [], i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }

</script>

</body>
</html>
